package com.shaoshaohuo.app.view;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v4.view.ViewPager.PageTransformer;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.adapter.AdPagerAdapter;
import com.shaoshaohuo.app.entity.AdModel;
import com.shaoshaohuo.app.ui.WebBrowserActivity;
import com.shaoshaohuo.app.utils.ImageLoadUtil;
import com.shaoshaohuo.app.utils.ViewUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 首页广告滚动栏
 *
 * @author YinSF
 * @createDate 2015-11-7
 */
public class AdViewPager extends LinearLayout implements OnPageChangeListener {


    private ViewPager viewPager;
    private LinearLayout llDots;

    //底部小店图片
    private ImageView[] dots;
    //当前被选中的序号
    private int currentIndex = 1;
    //图片个数
    private int imageCount = 0;

    private AdPagerAdapter adPagerAdapter;

    private static final int MSG_DEFAULT = 1;
    private static final int MSG_NEW_DATA = 2;


    private  Timer timer;


    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_DEFAULT:
                    if (adPagerAdapter == null)
                        return;
                    currentIndex += 1;
                    setCurDot(currentIndex % imageCount);
                    viewPager.setCurrentItem(currentIndex);
                    break;
                case MSG_NEW_DATA:
                    List<AdModel> list = (List<AdModel>) msg.obj;
                    setAdapter(requestImages(list));
                    break;
                default:
                    break;
            }
        }

    };
    //请求 图片
    private List<ImageView> requestImages(List<AdModel> list) {

        ImageLoader imageLoader = ImageLoader.getInstance();

        List<ImageView> images = new ArrayList<ImageView>();

        for (final AdModel am : list) {
            ImageView iv = new ImageView(getContext());
            ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
            iv.setLayoutParams(params);
            iv.setScaleType(ScaleType.FIT_XY);

            imageLoader.displayImage(am.getImageUrl(),
                    iv, ImageLoadUtil.build);
//            getDisplayImageOptions(R.drawable.banner_ec_ad)

            iv.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (TextUtils.isEmpty(am.getLinkUrl())) {
                        return;
                    }
                    Intent intent = new Intent(getContext(), WebBrowserActivity.class);
                    intent.putExtra(WebBrowserActivity.TITLE, am.getTitle());
                    intent.putExtra(WebBrowserActivity.URL, am.getLinkUrl());
                    getContext().startActivity(intent);
                }
            });
            images.add(iv);
        }
        return images;
    }

    public AdViewPager(Context context) {
        super(context);
        init();
    }

    public AdViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {

        initView();
        initAnimation();
//        setDefaultPicture();
    }

    private void startLoop() {

        if (timer == null) {
            timer = new Timer(true);
            timer.schedule(new TimerTask() {

                @Override
                public void run() {
                    handler.sendEmptyMessage(MSG_DEFAULT);
                }

            }, 1000, 7000);
        }

    }


    /**
     * 初始化视图组件
     */
    private void initView() {
        inflate(getContext(), R.layout.view_ad_view_pager, this);
        viewPager = (ViewPager) findViewById(R.id.adViewpager);
        llDots = (LinearLayout) findViewById(R.id.ll);

        viewPager.setOnPageChangeListener(this);
    }

    /**
     * 初始化动画
     */
    private void initAnimation() {
        viewPager.setPageTransformer(true, new PageTransformer() {
            private static final float MIN_SCALE = 0.85f;

            @Override
            public void transformPage(View view, float position) {
                int pageWidth = view.getWidth();

                if (position < -1) { // [-Infinity,-1)
                    // This page is way off-screen to the left.
                    view.setAlpha(0);

                } else if (position <= 0) { // [-1,0]
                    // Use the default slide transition when moving to the left page
                    view.setAlpha(1);
                    view.setTranslationX(0);
                    view.setScaleX(1);
                    view.setScaleY(1);

                } else if (position <= 1) { // (0,1]
                    // Fade the page out.
                    view.setAlpha(1 - position);

                    // Counteract the default slide transition
                    view.setTranslationX(pageWidth * -position);

                    // Scale the page down (between MIN_SCALE and 1)
                    float scaleFactor = MIN_SCALE
                            + (1 - MIN_SCALE) * (1 - Math.abs(position));
                    view.setScaleX(scaleFactor);
                    view.setScaleY(scaleFactor);

                } else { // (1,+Infinity]
                    // This page is way off-screen to the right.
                    view.setAlpha(0);
                }
            }
        });
    }


    /**
     * 默认数据
     */
    private void setDefaultPicture() {
        List<ImageView> images = new ArrayList<ImageView>();
        int[] ids = {};
        for (int id : ids) {
            ImageView iv = new ImageView(getContext());
            iv.setImageResource(id);
            ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
            iv.setLayoutParams(params);
            iv.setScaleType(ScaleType.FIT_XY);
            images.add(iv);
        }

        setAdapter(images);

    }


    /**
     * 设置视图
     */
    private void setAdapter(List<ImageView> ivList) {

        imageCount = ivList.size();
        currentIndex = imageCount * 1000;

        adPagerAdapter = new AdPagerAdapter(ivList);
        viewPager.setAdapter(adPagerAdapter);
        adPagerAdapter.notifyDataSetChanged();
        viewPager.setCurrentItem(currentIndex);

        setDots(imageCount);

        startLoop();
    }


    /**
     * 初始化数据
     */
    private void setDots(int newCount) {
        dots = new ImageView[newCount];
        llDots.removeAllViews();
        LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        params.gravity = Gravity.CENTER_VERTICAL;
        int dotPadding = ViewUtil.dip2px(getContext(), 15);
        //循环取得小点图片
        for (int i = 0; i < newCount; i++) {
            dots[i] = new ImageView(getContext());
            dots[i].setEnabled(true);//都设为灰色
//            dots[i].setOnClickListener(this);
            dots[i].setImageResource(R.drawable.dot);
//            dots[i].setClickable(true);
            dots[i].setPadding(dotPadding, dotPadding, dotPadding, dotPadding);
            dots[i].setTag(i);//设置位置tag，方便取出与当前位置对应
            llDots.addView(dots[i], params);
        }

        dots[currentIndex % imageCount].setEnabled(false);
    }


    /**
     * 设置、或刷新图片数据
     *
     * @param list
     */
    public void freshData(final List<AdModel> list) {
        if (list == null || list.isEmpty()) {
            return;
        }

        Message msg = new Message();
        msg.what = MSG_NEW_DATA;
        msg.obj = list;
        handler.sendMessage(msg);


    }


    @Override
    public void onPageScrollStateChanged(int arg0) {

    }

    @Override
    public void onPageSelected(int position) {
        if (imageCount == 0 || dots == null) {
            return;
        }
        currentIndex = position;
        setCurDot(currentIndex % imageCount);
    }

    private void setCurDot(int position) {
        for (int i = 0; i < dots.length; i++) {
            if (i == position) {
                dots[i].setEnabled(false);
            } else {
                dots[i].setEnabled(true);
            }
        }
    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
    }

}
